import { getToken } from '@/utils/token'
import Vue from 'vue'
import VueRouter from 'vue-router'
/* import Login from '@/views/login'
import Layout from '@/views/layout'
import Home from '@/views/home'
import User from '@/views/user'
import Search from '@/views/search'
import SearchResult from '@/views/search/searchResult'
import ArticleDetail from '@/views/articleDetail'
import UserEditor from '@/views/user/userEdit'
import Chat from '@/views/chat' */

Vue.use(VueRouter)

/**
 * * 总结:
 * ? 路由懒加载: 为了让第一个页面，加载的app.js小一点，打开网页快一点
 * TODO 思路: 把组件对应js，分成若干个.js，路由切换到哪个页面，才去加载对应的.js文件
 * ! 原因: webpack分析入口时，发现router里上来就import所有页面，所以直接打包进app.js -> 很大
 * * 解决: 当路由路径匹配规则时，才现去import引入对应的组件js文件
 */

const routes = [
  { path: '/', redirect: '/layout' },
  // 登录页
  // { path: '/login', component: Login },
  {
    path: '/login',
    component: () => import('@/views/login'),
    beforeEnter (to, from, next) {
      if (getToken()?.length > 0) { next('/') } else next()
    }
  },
  // 主页
  {
    path: '/layout',
    // component: Layout,
    component: () => import('@/views/layout'),
    redirect: '/layout/home',
    children: [
      // { path: 'home', component: Home },
      {
        path: 'home',
        component: () => import('@/views/home'),
        meta: {
          scrollT: 0 // 保存首页离开时滚动条的位置
        }
      },
      // { path: 'user', component: User }
      { path: 'user', component: () => import('@/views/user') }
    ]
  },
  // 搜索页
  {
    path: '/search',
    // component: Search
    component: () => import('@/views/search')
  },
  // 搜索结果页
  // { path: '/searchResult/:kw', component: SearchResult },
  { path: '/searchResult/:kw', component: () => import('@/views/search/searchResult') },

  // 文章详情页
  // { path: '/articlesDetail/:art_id', component: ArticleDetail },
  { path: '/articlesDetail/:art_id', component: () => import('@/views/articleDetail') },

  // 编辑资料页
  // { path: '/userEditor', component: UserEditor },
  { path: '/userEditor', component: () => import('@/views/user/userEdit') },

  // 小思同学页
  // { path: '/chat', component: Chat }
  { path: '/chat', component: () => import('@/views/chat') }

]

const router = new VueRouter({
  routes
})

/**
 * * 路由 - 全局前置守卫
 * ? 此函数可以决定路由是否 跳转/ 取消/ 强制中断切换到别的路由
 */
/* router.beforeEach((to, from, next) => {
  // 如果已经登录，不能进到登录页
  if (getToken()?.length > 0 && to.path === '/login') { next('/') } else next()
}) */

export default router
